import * as actionTypes from './actionTypes';
import {Toast} from 'antd-mobile';

const mutations = {
  setCategory: value => ({
    type: actionTypes.SET_CATEGORY,
    categoryList: value
  }),
  setExcellentBooks: value => ({
    type: actionTypes.SET_EXCELLENTBOOKS,
    excellentBooks: value
  }),
  setTotal: value => ({
    type: actionTypes.SET_TOTAL,
    total: value
  }),
  setCurrentPage: value => ({
    type: actionTypes.SET_CURRENTPAGE,
    currentPage: value
  }),
  setNewBooks: value => ({
    type: actionTypes.SET_NEWBOOKS,
    newBooks: value
  }),
  setHotBooks: value => ({
    type: actionTypes.SET_HOTBOOKS,
    hotBooks: value
  })
};

const actions = {
  /**
   * 获取分类列表
   */
  getCategoryAct: () => {
    return (dispatch,getState) => {
      // Toast.loading('加载中...',1);
      fetch("http://106.52.37.222:3000/category")
      .then(response => response.json())
      .then(res => {
        // console.log(res);
        dispatch(mutations.setCategory(res));
      })
    }
  },
  /**
   * 获取精品书籍列表
   */
  getExcellentBooksAct: (payload) => {
    return (dispatch,getState) => {
      let page = payload.page;
      let pageSize = payload.pageSize;
      let total = getState().book.total;
      // Toast.loading('加载中...',1);
      fetch(`http://106.52.37.222:3000/excellentBooks?_page=${page}&_limit=${pageSize}`)
      .then(response => {
        // console.log(response);
        total = parseInt(response.headers.get('X-Total-Count'));
        return response.json();
      })
      .then(res => {
        dispatch(mutations.setExcellentBooks(res));
        dispatch(mutations.setTotal(total));
        dispatch(mutations.setCurrentPage(page));
      })
    }
  },
  /**
   * 获取新书籍列表
   */
  getNewBooksAct: (payload) => {
    return (dispatch,getState) => {
      let page = payload.page;
      let pageSize = payload.pageSize;
      let total = getState().book.total;
      // Toast.loading('加载中...',1);
      fetch(`http://106.52.37.222:3000/newBooks?_page=${page}&_limit=${pageSize}`)
      .then(response => {
        // console.log(response);
        total = parseInt(response.headers.get('X-Total-Count'));
        return response.json();
      })
      .then(res => {
        dispatch(mutations.setNewBooks(res));
        dispatch(mutations.setTotal(total));
        dispatch(mutations.setCurrentPage(page));
      })
    }
  },
  /**
   * 获取火爆书籍列表
   */
  getHotBooksAct: () => {
    return (dispatch,getState) => {
      fetch('http://106.52.37.222:3000/hot')
      .then(response => response.json())
      .then(res => {
        dispatch(mutations.setHotBooks(res));
      })
    }
  }
};

export default actions;
